package soul.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import soul.domain.response.AuthParam;
import soul.entity.User;
import soul.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by admin on 2016/11/26.
 */
@Component
public class AuthFilter implements Filter {

    @Autowired
    private UserService service;
    private static ThreadLocal<Map<String, Object>> LOCAL_VARS = new ThreadLocal<Map<String, Object>>();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String uri = ((HttpServletRequest) request).getRequestURI();
        if(uri.contains("articles")){
            chain.doFilter(request, response);
            return;
        }
        if (uri.contains("login")) {
            chain.doFilter(request, response);
            return;
        }
        if (uri.contains("verification_code")) {
            chain.doFilter(request, response);
            return;
        }
        if (uri.contains("guest")) {
            chain.doFilter(request, response);
            return;
        }
        User userGot = null;
        try {
            String credential = ((HttpServletRequest) request).getHeader("X-AUTH-TOKEN");
            AuthParam param = new ObjectMapper().readValue(credential, AuthParam.class);
            userGot = service.checkUserCredential(param.getUser());
        } catch (Exception e) {
            
        }
        setVar("user", userGot);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    private static void setVar(String key, Object obj) {
        Map<String, Object> stringObjectMap = LOCAL_VARS.get();
        if (null == stringObjectMap) {
            stringObjectMap = new HashMap<>();
            LOCAL_VARS.set(stringObjectMap);
        }
        stringObjectMap.put(key, obj);
    }

    public static Object getVar(String key) {
        Map<String, Object> stringObjectMap = LOCAL_VARS.get();
        return null != stringObjectMap ? stringObjectMap.get(key) : null;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}
